﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace DimensionData
{
    public class DimTree
    {
        /// <summary>
        /// 对应的维度数据
        /// </summary>
        public List<DimData> Nodes { get; set; }

        /// <summary>
        /// 与下级维度的关联关系
        /// </summary>
        public DimRelation Relation { get; set; }

        /// <summary>
        /// 下级维度树
        /// </summary>
        public DimTree NextTree { get; set; }

        public DimTree(List<DimData> dims)
        {
            Nodes = dims;
        }

        public DimView GetView()
        {
            if (Relation != null)
            {
                //Relation.Pull();
            }
            //return new D01View(Nodes);
            return null;
        }

        public DimRelation Relate(DimTree dimTree)
        {
            DimRelation relation = new DescartesRelation(this, dimTree);

            Relation = relation;
            NextTree = dimTree;

            return relation;
        }

        public List<DimTreeNode> Dump()
        {
            List<DimTreeNode> nodes = new List<DimTreeNode>();

            List<DimTreeNode> tempNodes = new List<DimTreeNode>();

            DimView view = new D01View(Nodes);
            List<DimViewItem> items = view.Items;
            foreach (var item in items)
            {
                DimTreeNode node = new DimTreeNode();
                node.Range = item.Range;
                node.DimData = item.DimData;
                //node.Items.Add(item);
                tempNodes.Add(node);
            }

            if (this.NextTree != null)
            {
                for (int index = tempNodes.Count - 1; index >= 0; index--)
                {
                    DimTreeNode tempNode = tempNodes[index];

                    List<DimTreeNode> subNodes = Relation.Pull(tempNode);

                    for (int subIndex = subNodes.Count - 1; subIndex >= 0; subIndex--)
                    {
                        DimTreeNode subNode = subNodes[subIndex];

                        DimTreeNode node = tempNode.Clone();
                        node.Range = (subNodes.Count) * node.Range + (subNodes.Count - subIndex - 1);// subNode.Range;
                        node.Next = subNode;
                        //node.Items.AddRange(subNode.Items);
                        nodes.Insert(0, node);
                    }
                }
            }
            else
            {
                nodes = tempNodes;
            }
            return nodes;
        }
    }
}
